import React, { useState, useMemo } from "react";
// useMemo的写法和useCallback一摸一样
// useMemo返回的是属性

// useMemo功能和vue的计算属性是一样的

// useCallback和useMemo的区别
// 1. useCallback是当有父子组件，父组件有一个事件要传递给子组件的时候用，useMemo是需要使用计算属性的时候用
// 2. 他们都是有缓存的，useCallback缓存的是整个函数，而useMemo缓存的是函数的返回值
// 3. useCallback是可以改写成useMemo，useMemo是不能改写成useCallback的

const App = () => {
  const [count, setCount] = useState(1);
  const [num, setNum] = useState(10);

  const [arr] = useState([1, 2, 3, 4, 5, 6, 7]);

  const add = () => {
    setCount((v) => v + 1);
  };
  const add2 = () => {
    setNum((v) => v + 1);
  };

  const sum = useMemo(() => {
    console.log("sum");
    let s = 0;
    for (let i = 0; i <= count * 100; i++) {
      s += i;
    }
    return s;
  }, [count]);

  const oddArr = useMemo(() => {
    return arr.filter((item) => item % 2);
  }, [arr]);

  return (
    <>
      <h2>useMemo</h2>
      <p>count: {count}</p>
      <p>sum: {sum}</p>
      <button onClick={add}>btn</button>

      <p>num: {num}</p>
      <button onClick={add2}>btn2</button>

      <ul>
        {oddArr.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
    </>
  );
};

export default App;
